﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Data.Objects;

namespace Nectar.DAL.Common
{
    public class Utility
    {
        public static String toPlural(String name)
        {
            String plural;
            if (name != null && name.Length > 0)
            {
                char ch = name[name.Length - 1];
                StringBuilder pluralBuilder = new StringBuilder(name);
                pluralBuilder.Append("set");
                plural = pluralBuilder.ToString();
            }
            else
            {
                plural = name;
            }
            return plural;
        }

        public static Type GetBaseType(Type type)
        {
            if (type.BaseType != null)
            {
                if (type.BaseType.Name == "EntityObject")
                {
                    return type;
                }
                else
                    return GetBaseType(type.BaseType);
            }
            else
                return null;
        }

        /// <summary>
        /// 序列化状态对象
        /// </summary>
        /// <param name="state">状态对象</param>
        /// <returns>状态对象的序列化值</returns>
        public static string Serialize<T>(T t)
        {
            string content = null;
            using (MemoryStream ms = new MemoryStream())
            {
                var serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(ms, t);
                ms.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(ms);
                content = reader.ReadToEnd();
            }

            return content;
        }
        /// <summary>
        /// 反序列化状态对象
        /// </summary>
        /// <param name="state">状态对象的序列化值</param>
        /// <returns>状态对象</returns>
        public static T Deserialize<T>(string XString)
        {
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(XString)))
            {
                var serializer = new DataContractSerializer(typeof(T));
                T theObject = (T)serializer.ReadObject(stream);
                return theObject;
            }
        }

        /// <summary>  
        ///  JSON序列化  
        /// </summary>   
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            //替换Json的Date字符串  
            //string p = @"\\/Date\((\d+)\+\d+\)\\/";
            //MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            //Regex reg = new Regex(p);
            //jsonString = reg.Replace(jsonString, matchEvaluator);
            return jsonString;
        }
        /// <summary>  
        /// JSON反序列化  
        ///  </summary>  
        public static T JsonDeserialize<T>(string jsonString)
        {
            //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式 
            //string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            //MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            //Regex reg = new Regex(p);
            //jsonString = reg.Replace(jsonString, matchEvaluator);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }

        public static string PrepareExpression(string esql, string expression)
        {
            if (string.IsNullOrEmpty(expression) || expression.Trim() == "")
                return esql + " where o.IsDel=false";
            if (expression.ToLower().TrimStart().IndexOf("order") == 0 || expression.ToLower().TrimStart().IndexOf("skip") == 0 || expression.ToLower().TrimStart().IndexOf("limit") == 0)
                esql += " where o.IsDel=false " + expression;
            else
            {
                //默认增加isdel=0的查询条件
                if (expression.IndexOf("o.IsDel") < 0)
                    esql += " where o.IsDel=false and " + expression;
                else
                    esql += " where " + expression;
            }
            return esql;
        }

        public static string PrepareSql<TEntity>(string property, string expression)
        {
            string esql = "";
            if (string.IsNullOrWhiteSpace(property))
                property = "value o";
            Type baseType = Utility.GetBaseType(typeof(TEntity));
            if (baseType.Name == typeof(TEntity).Name)
                esql = "select " + property + " from " + Utility.toPlural(typeof(TEntity).Name) + " as o ";
            else
                esql = "select " + property + " from OfType(" + Utility.toPlural(baseType.Name) + "," + typeof(TEntity).FullName + ") as o ";
            return PrepareExpression(esql, expression);
        }

        public static ObjectParameter[] PrepareParameter(QueryParameter[] queryParameters)
        {
            ObjectParameter[] parameters;
            if (queryParameters == null)
                parameters = new ObjectParameter[0];
            else
            {
                parameters = new ObjectParameter[queryParameters.Length];
                for (int i = 0; i < queryParameters.Length; i++)
                {
                    parameters[i] = new ObjectParameter(queryParameters[i].Name, queryParameters[i].Value);
                }
            }
            return parameters;
        }
    }
}
